/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.jprvyd.gui.form;

import cz.muni.fi.pb138.jprvyd.Address;
import cz.muni.fi.pb138.jprvyd.Contact;
import cz.muni.fi.pb138.jprvyd.ContactManager;
import cz.muni.fi.pb138.jprvyd.ContactManagerImpl;
import cz.muni.fi.pb138.jprvyd.gui.list.ContactList;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author Jan
 */
public class ContactForm extends javax.swing.JFrame {

    SwingWorker swingWorker;
    public static final boolean EDIT = true;
    public static final boolean ADD = false;
    private boolean action;
    ContactList contactList;
    Contact contact;
    ContactManager contactManager;

    /**
     * Creates new form ContactForm
     */
    public ContactForm() {
        contactManager = new ContactManagerImpl();
        initComponents();
    }

    public ContactForm(ContactList contactList) {
        contactManager = new ContactManagerImpl();
        this.contactList = contactList;
        action = ADD;
        initComponents();
    }

    public ContactForm(ContactList contactList, Contact contact) {
        contactManager = new ContactManagerImpl();
        this.contactList = contactList;
        this.contact = contact;
        action = EDIT;
        initComponents();
        textFieldBankAcc.setText(contact.getBankAccount());
        textFieldCity.setText(contact.getAddress().getCity());
        textFieldCountry.setText(contact.getAddress().getCountry());
        textFieldDIC.setText(contact.getDic());
        textFieldFirstName.setText(contact.getFirstName());
        textFieldICO.setText(new Integer(contact.getIco()).toString());
        textFieldStreet.setText(contact.getAddress().getStreet());
        textFieldSurname.setText(contact.getSurname());
        textFieldZIP.setText(new Integer(contact.getAddress().getZip()).toString());
    }

    public ContactForm(Contact contact) {
        contactManager = new ContactManagerImpl();
        this.contact = contact;
        action = EDIT;
        initComponents();
        textFieldBankAcc.setText(contact.getBankAccount());
        textFieldCity.setText(contact.getAddress().getCity());
        textFieldCountry.setText(contact.getAddress().getCountry());
        textFieldDIC.setText(contact.getDic());
        textFieldFirstName.setText(contact.getFirstName());
        textFieldICO.setText(new Integer(contact.getIco()).toString());
        textFieldStreet.setText(contact.getAddress().getStreet());
        textFieldSurname.setText(contact.getSurname());
        textFieldZIP.setText(new Integer(contact.getAddress().getZip()).toString());
    }

    private class addSwingWorker extends SwingWorker<Integer, Void> {

        ContactList contactList;
        Contact contact;
        ContactManager contactManager;

        public addSwingWorker(ContactList contactList, Contact contact, ContactManager contactManager) {
            this.contact = contact;
            this.contactList = contactList;
            this.contactManager = contactManager;
        }

        @Override
        protected Integer doInBackground() throws Exception {

            contactManager.createContact(contact);

            if (contactList != null) {
                contactList.refreshContacts(contact, contactList.ADD);
            }

            return 0;
        }

        @Override
        protected void done() {
            buttonSave.setEnabled(true);
            swingWorker = null;
        }
    }

    private class editSwingWorker extends SwingWorker<Integer, Void> {

        Contact newContact;
        ContactList contactList;
        ContactManager contactManager;

        public editSwingWorker(Contact newContact, ContactList contactList, ContactManager contactManager) {
            this.contactManager = contactManager;
            this.newContact = newContact;
            this.contactList = contactList;

        }

        @Override
        protected Integer doInBackground() throws Exception {

            contactManager.updateContact(newContact);

            if (contactList != null) {
                contactList.refreshContacts(newContact, contactList.EDIT);
            }

            return 0;
        }

        @Override
        protected void done() {
            buttonSave.setEnabled(true);
            swingWorker = null;
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        labelFirstName = new javax.swing.JLabel();
        labelSurname = new javax.swing.JLabel();
        labelStreet = new javax.swing.JLabel();
        labelCity = new javax.swing.JLabel();
        labelZIP = new javax.swing.JLabel();
        labelCountry = new javax.swing.JLabel();
        labelICO = new javax.swing.JLabel();
        labelDIC = new javax.swing.JLabel();
        labelBankAcc = new javax.swing.JLabel();
        textFieldBankAcc = new javax.swing.JTextField();
        textFieldDIC = new javax.swing.JTextField();
        textFieldICO = new javax.swing.JTextField();
        textFieldCountry = new javax.swing.JTextField();
        textFieldZIP = new javax.swing.JTextField();
        textFieldCity = new javax.swing.JTextField();
        textFieldStreet = new javax.swing.JTextField();
        textFieldSurname = new javax.swing.JTextField();
        textFieldFirstName = new javax.swing.JTextField();
        buttonSave = new javax.swing.JButton();
        buttonCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("JPrVyd - Managing contacts");

        labelFirstName.setText("First name:");

        labelSurname.setText("Surname:");

        labelStreet.setText("Street:");

        labelCity.setText("City:");

        labelZIP.setText("ZIP code:");

        labelCountry.setText("Country:");

        labelICO.setText("ICO:");

        labelDIC.setText("DIC:");

        labelBankAcc.setText("Bank account:");

        buttonSave.setText("Save");
        buttonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveActionPerformed(evt);
            }
        });

        buttonCancel.setText("Cancel");
        buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(labelFirstName)
                        .addGap(18, 18, 18)
                        .addComponent(textFieldFirstName))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelBankAcc)
                            .addComponent(labelDIC)
                            .addComponent(labelICO)
                            .addComponent(labelCountry)
                            .addComponent(labelZIP)
                            .addComponent(labelStreet)
                            .addComponent(labelCity)
                            .addComponent(labelSurname))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(textFieldSurname)
                            .addComponent(textFieldStreet)
                            .addComponent(textFieldCity)
                            .addComponent(textFieldZIP)
                            .addComponent(textFieldCountry)
                            .addComponent(textFieldICO)
                            .addComponent(textFieldDIC)
                            .addComponent(textFieldBankAcc, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(buttonSave)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(buttonCancel)
                .addGap(24, 24, 24))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelFirstName)
                    .addComponent(textFieldFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelSurname)
                    .addComponent(textFieldSurname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelStreet)
                    .addComponent(textFieldStreet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelCity)
                    .addComponent(textFieldCity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelZIP)
                    .addComponent(textFieldZIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(labelCountry)
                            .addComponent(textFieldCountry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(24, 24, 24)
                        .addComponent(labelICO))
                    .addComponent(textFieldICO, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelDIC)
                    .addComponent(textFieldDIC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelBankAcc)
                    .addComponent(textFieldBankAcc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonSave)
                    .addComponent(buttonCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed
        if (swingWorker != null) {
            throw new IllegalStateException("Operation in progress");
        } else {
            if (action == ADD) {
                Contact newContact = parseTextFields();
                if (newContact != null) {
                    swingWorker = new addSwingWorker(contactList, newContact, contactManager);
                    buttonSave.setEnabled(false);
                    swingWorker.execute();
                    this.dispose();
                }
            } else if (action == EDIT) {
                Contact newContact = parseTextFields();
                if (newContact != null) {
                    newContact.setId(contact.getId());
                    swingWorker = new editSwingWorker(newContact, contactList, contactManager);
                    buttonSave.setEnabled(false);
                    swingWorker.execute();
                    this.dispose();
                }
            }
        }
    }//GEN-LAST:event_buttonSaveActionPerformed

    private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_buttonCancelActionPerformed

    private Contact parseTextFields() {
        String firstName = textFieldFirstName.getText();
        String surname = textFieldSurname.getText();
        String street = textFieldStreet.getText();
        String city = textFieldCity.getText();
        String zipString = textFieldZIP.getText();
        String country = textFieldCountry.getText();
        String dic = textFieldDIC.getText();
        String icoString = textFieldICO.getText();
        String bankAccount = textFieldBankAcc.getText();
        int ico = 0;
        int zip = 0;
        if (firstName.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter (first) name");
        } else if (street.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter street");
        } else if (city.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter city");
        } else if (zipString.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter ZIP code");
        } else if (country.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter country");
        } else if (icoString.equals("") && dic.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter ICO or DIC");
        } else {
            boolean ok = true;
            if (!zipString.equals("")) {
                try {
                    zip = Integer.parseInt(zipString);
                } catch (NumberFormatException e) {
                    ok = false;
                    JOptionPane.showMessageDialog(rootPane, "Enter correct zip (5 digit number)");
                }
                if (zip > 99999 || zip < 10000) {
                    JOptionPane.showMessageDialog(rootPane, "Enter correct zip (5 digit number)");
                    ok = false;
                }
            }
            if (!icoString.equals("")) {
                try {
                    ico = Integer.parseInt(icoString);
                } catch (NumberFormatException e) {
                    ok = false;
                    JOptionPane.showMessageDialog(rootPane, "Enter correct ICO");
                }
            }
            
            if (ok) {

                Address address = new Address();
                Contact newContact = new Contact();
                address.setCity(city);
                address.setCountry(country);
                address.setStreet(street);
                address.setZip(zip);
                newContact.setAddress(address);
                newContact.setBankAccount(bankAccount);
                newContact.setDic(dic);
                newContact.setFirstName(firstName);
                newContact.setIco(ico);
                newContact.setSurname(surname);

                return newContact;
            }             
        }
        return null;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ContactForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ContactForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ContactForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ContactForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ContactForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCancel;
    private javax.swing.JButton buttonSave;
    private javax.swing.JLabel labelBankAcc;
    private javax.swing.JLabel labelCity;
    private javax.swing.JLabel labelCountry;
    private javax.swing.JLabel labelDIC;
    private javax.swing.JLabel labelFirstName;
    private javax.swing.JLabel labelICO;
    private javax.swing.JLabel labelStreet;
    private javax.swing.JLabel labelSurname;
    private javax.swing.JLabel labelZIP;
    private javax.swing.JTextField textFieldBankAcc;
    private javax.swing.JTextField textFieldCity;
    private javax.swing.JTextField textFieldCountry;
    private javax.swing.JTextField textFieldDIC;
    private javax.swing.JTextField textFieldFirstName;
    private javax.swing.JTextField textFieldICO;
    private javax.swing.JTextField textFieldStreet;
    private javax.swing.JTextField textFieldSurname;
    private javax.swing.JTextField textFieldZIP;
    // End of variables declaration//GEN-END:variables
}
